﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using EasyStudy.Logic;
using EasyStudy.Properties;
using ComponentFactory.Krypton.Toolkit;
using EasyStudy.tools;
using EasyStudy.Logic.Remind;

namespace EasyStudy.UI
{
    public partial class FrmRemind : KryptonForm
    {
        int totalTaskNumber = 0;
        int screenWidth = SystemInformation.WorkingArea.Width;
        int scrollWidth = SystemInformation.VerticalScrollBarWidth;
        int screenHeight = SystemInformation.WorkingArea.Height;
        string lastSelectPageKey = string.Empty;                    // 用户最后一次选择的TabPage Key

        public FrmRemind()
        {
            InitializeComponent();
            Icon = Resources.task1;
            this.AutoSize = false;
            this.AutoScroll = true;

            this.FormClosing += new FormClosingEventHandler(FrmRemind_FormClosing);
            GlobalSettings.AllowPopupValueChanged += new EventHandler(GlobalSettings_AllowPopupValueChanged);
            chkDontPopup.Checked = !GlobalSettings.AllowPopup;
            chkCloseSound.Checked = !GlobalSettings.SoundOn;
        }

        void GlobalSettings_AllowPopupValueChanged(object sender, EventArgs e)
        {
            chkDontPopup.Checked = !GlobalSettings.AllowPopup;
        }

        void FrmRemind_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            Visible = false;
        }

        public void LoadPreviousTasks(List<EbbinghausTask> tasks)
        {
            LoadTasks(tasks, true);
            totalTaskNumber += tasks.Count;
        }

        public void ClearControls()
        {
            tabControl.TabPages.Clear();
            for (int i = 0; i < tabControl.TabPages.Count; ++i)
            {
                TabPage tp = tabControl.TabPages[i];
                if (tp != null && !tp.IsDisposed)
                {
                    // 释放TabPage中的组件
                    for (int j = 0; j < tp.Controls.Count; ++j)
                    { 
                        Control c = tp.Controls[j];
                        if (c != null && !c.IsDisposed)
                        {
                            c.Dispose();
                            c = null;
                            tp.Controls.RemoveAt(j);
                        }
                    }
                    tp.Dispose();
                    tp = null;
                    tabControl.TabPages.RemoveAt(i);
                }
            }
 
            totalTaskNumber = 0;
            System.GC.Collect();
        }

        public void LoadTodayTask(List<EbbinghausTask> tasks)
        {
            LoadTasks(tasks, false);
            totalTaskNumber += tasks.Count;
            Text = "您有" + totalTaskNumber + "个任务需要更新！";
        }

        /// <summary>
        /// 获取所有任务的类型名称
        /// </summary>
        /// <param name="tasks"></param>
        /// <returns></returns>
        public List<string> getCategoryNames(List<EbbinghausTask> tasks)
        {
            List<string> categoryNames = new List<string>();

            foreach (EbbinghausTask ebbTask in tasks)
            {
                if (categoryNames.Contains(ebbTask.Type))
                {
                    continue;
                }
                else
                {
                    categoryNames.Add(ebbTask.Type);
                }
            }

            return categoryNames;
        }

        private void LoadTasks(List<EbbinghausTask> tasks, bool isPastTask)
        {
            // 创建页面
            foreach(string type in getCategoryNames(tasks)) 
            {
                if (!tabControl.TabPages.ContainsKey(type))
                {
                    if (type.Trim() == string.Empty)
                    {
                        if (tabControl.TabPages["默认"] == null)
                        {
                            tabControl.TabPages.Add("默认", "默认");
                            tabControl.TabPages["默认"].AutoScroll = true;
                        }
                    }
                    else
                    {
                        tabControl.TabPages.Add(type, type);
                        tabControl.TabPages[type].AutoScroll = true;
                    }
                }
            }
            
            List<CtrlTodoTaskEx> listTodoTask = new List<CtrlTodoTaskEx>();
            // 保存第一或第二周期需要更新的任务
            List<CtrlTodoTaskEx> topTodoTask = new List<CtrlTodoTaskEx>();

            foreach (EbbinghausTask task in tasks)
            {
                //CtrlTodoTask todoTask = new CtrlTodoTask(task);
                CtrlTodoTaskEx todoTask = new CtrlTodoTaskEx(task);

                todoTask.Dock = DockStyle.Top;
                todoTask.UpdateTask += new EventHandler(todoTask_UpdateTask);
                if (isPastTask)
                {
                    todoTask.SetPastTaskStyle();
                }

                // 如果任务是第一或第二周期Update，将其放在顶部
                if (todoTask.Task.NextIndex < 2)
                {
                    topTodoTask.Add(todoTask);
                }
                else
                {
                    listTodoTask.Add(todoTask);
                }
            }

            foreach(CtrlTodoTaskEx todoTask in listTodoTask)
            {
                if (todoTask.Task.Type.Trim() == string.Empty)
                {
                    tabControl.TabPages["默认"].Controls.Add(todoTask);
                }
                else
                {
                    tabControl.TabPages[todoTask.Task.Type].Controls.Add(todoTask);
                }
            }

            foreach (CtrlTodoTaskEx todoTask in topTodoTask)
            {
                if (todoTask.Task.Type.Trim() == string.Empty)
                {
                    tabControl.TabPages["默认"].Controls.Add(todoTask);
                }
                else
                {
                    tabControl.TabPages[todoTask.Task.Type].Controls.Add(todoTask);
                }
            }
        }

        public void selectLastSelectedTabPage()
        {
            string selectCriticalTask = string.Empty;

            // 判断那个Tab里有第一或第二周期需要更新的任务
            if (tabControl.TabPages.Count > 0)
            {
                foreach (TabPage tp in tabControl.TabPages)
                {
                    if (tp.Controls.Count > 0)
                    { 
                        foreach(Control todoTask in tp.Controls)
                        {
                            CtrlTodoTaskEx todoTaskCtrl = (CtrlTodoTaskEx)todoTask;
                            if (todoTaskCtrl.Task.NextIndex < 2)
                            {
                                selectCriticalTask = tp.Name;
                            }
                        }
                    }
                }
            }

            if (selectCriticalTask == string.Empty)
            {
                // 选择上次最后一次选择TabPage
                if (tabControl.TabPages.ContainsKey(lastSelectPageKey))
                {
                    tabControl.SelectedTab = tabControl.TabPages[lastSelectPageKey];
                }
            }
            else
            {
                // 选择上次最后一次选择TabPage
                if (tabControl.TabPages.ContainsKey(selectCriticalTask))
                {
                    tabControl.SelectedTab = tabControl.TabPages[selectCriticalTask];
                }
            }
        }

        public void PackSize()
        {
            int captionHeight = SystemInformation.CaptionHeight;
            int borderHeight = SystemInformation.BorderSize.Height;
            this.AutoSize = false;

            // 获取工具条的高度
            int toolBarHeight = pnlButtons.Height;
            // 获取当前Page任务数
            TabPage tp = tabControl.SelectedTab;

            if (tp == null)
            {
                if (tabControl.TabPages.Count > 0)
                {
                    tp = tabControl.TabPages[0];
                }
            }

            int taskCount = 0;

            if (tp != null)
            {
                taskCount = tabControl.SelectedTab.Controls.Count;

                if (taskCount == 0)
                {
                    if (tabControl.SelectedTab != null)
                    {
                        tabControl.Controls.Remove(tabControl.SelectedTab);
                    }
                }

                // 最多显示4个
                if (taskCount > 4)
                {
                    this.Height = toolBarHeight + (tabControl.SelectedTab.Controls[0].Height) * 4 + captionHeight + borderHeight + 43;
                }
                else
                {
                    this.Height = toolBarHeight + (tabControl.SelectedTab.Controls[0].Height) * taskCount + captionHeight + borderHeight + 43;
                }
            }

            //if (maxTasksInPage > 0)
            //{
            //    int baseHeight = panel.Controls[0].Height + 40;

            //    // 只显示<=4个任务，其他的使用滚动条
            //    if (maxTasksInPage > 3)
            //    {
            //        this.Height = 4 * baseHeight + captionHeight + borderHeight + 75;
            //    }
            //    else
            //    {
            //        this.Height = maxTasksInPage * baseHeight + captionHeight + borderHeight + 75;
            //    }
            //}

            // 设置窗口位置(右下角)
            this.Location = new Point(screenWidth - Width - scrollWidth, screenHeight - Height);
            Text = "您有" + totalTaskNumber + "个任务需要更新！";
        }

        void todoTask_UpdateTask(object sender, EventArgs e)
        {
            KryptonButton btnUpdate = (KryptonButton)sender;
            //CtrlTodoTask ctrlTodoTask = (CtrlTodoTask)(btnUpdate.Parent.Parent.Parent);
            CtrlTodoTaskEx ctrlTodoTask = (CtrlTodoTaskEx)(btnUpdate.Parent.Parent.Parent.Parent);

            EbbTaskDBMgr.FinishATask(ctrlTodoTask.Task);
            ctrlTodoTask.SetFinishStatus();
            //Controls.Remove(ctrlTodoTask);

            if (tabControl.SelectedTab != null)
            {
                lastSelectPageKey = tabControl.SelectedTab.Text;
            }
        }

        private void chkCloseSound_CheckedChanged(object sender, EventArgs e)
        {
            GlobalSettings.SoundOn = !this.chkCloseSound.Checked;
            if (!GlobalSettings.SoundOn)
            {
                Sound.Stop();
            }
        }

        private void chkDontPopup_CheckedChanged(object sender, EventArgs e)
        {
            GlobalSettings.AllowPopup = !this.chkDontPopup.Checked;
        }

        private void btnFresh_Click(object sender, EventArgs e)
        {
            FrmSimple.checker.Check();
            DBAutoBackup.StartBackup();
        }

        private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            PackSize();
        }
    }
}
